package com.easyapi.job;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easyapi.common.bean.ApiCenterInterfaceInfo;
import com.easyapi.common.emun.InterfaceInfoEnum;
import com.easyapi.config.DynamicApiConfig;
import com.easyapi.config.PoolConfig;
import com.easyapi.mapper.ApiCenterInterfaceInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;

/**
 * @author javadadi
 */
@Component
@Slf4j
public class APiPathJob {
    @Resource
    private ApiCenterInterfaceInfoMapper infoMapper;

    @Resource
    private DynamicApiConfig dynamicApiConfig;

    private static final Integer SEARCH_BATH_SIZE = 500;
    /**
     * 定时更新一下api_path
     */
    @PostConstruct
    @Scheduled(cron = "0 22 12 */5 * ?")
    public void initPath() {
        PoolConfig.RUN_SYNC_JOB_POOL.execute(()->{
            log.info("update path start {}",System.currentTimeMillis());
            //get
            Map<String,Long> pathMap = new HashMap<>(64);
            Map<String, Long> getMap = listPath(InterfaceInfoEnum.REQ_TYPE_GET.getCode());
            List<String> getRegistered = dynamicApiConfig.getAlreadyRegistered(RequestMethod.GET);
            for (String path : getRegistered) {
                getMap.remove(path);
            }
            List<String> getPath = new ArrayList<>(getMap.keySet());
            //post
            Map<String, Long> postMap = listPath(InterfaceInfoEnum.REQ_TYPE_POST.getCode());
            List<String> postRegistered = dynamicApiConfig.getAlreadyRegistered(RequestMethod.POST);
            for (String path : postRegistered) {
                postMap.remove(path);
            }
            List<String> postPath = new ArrayList<>(postMap.keySet());
            try {
                dynamicApiConfig.registerDynamicApiRoutesGET(getPath);
                dynamicApiConfig.registerDynamicApiRoutesPOST(postPath);
            } catch (NoSuchMethodException e) {
                log.error(e.getMessage());
            }
            log.info("update path end {}",System.currentTimeMillis());
        });
    }


    public Map<String,Long> listPath(Integer reqType){
        Map<String,Long> map = new HashMap<>();
        for (int current = 0; ; current++) {
            Page<ApiCenterInterfaceInfoMapper> page = new Page<>(current, SEARCH_BATH_SIZE);
            List<ApiCenterInterfaceInfo> records = infoMapper.getAllInterfaceInfo(page).getRecords();
            if(CollectionUtils.isEmpty(records)) break;
            records.forEach(record -> {
                map.put(record.getApiPath(),record.getId());
            });
        }
        return map;
    }
}
